package com.ly.mpayment.rest.system;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.matchingstrategy.IMatchingStrategyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.core.util.BigUtil;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.CookieRedis;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.ExportExcelUtil;
import com.ly.mpayment.core.util.JsonUtils;
import com.ly.mpayment.core.util.MapUtil;
import com.ly.mpayment.core.util.RedisUtil;
import com.ly.mpayment.core.util.ResultMessage;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.core.util.UserUtil;
import com.ly.mpayment.persist.service.businesstype.IBusinessTypeService;
import com.ly.mpayment.persist.service.operators.IOperatorsService;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@Path("system/upproduct/")
public class UpProductRest extends AbsRest {
	Logger logger = Logger.getLogger(UpProductRest.class);

	@Autowired
	IUserService userService;

	@Autowired
	IProvincialInformationService proService;

	@Autowired
	IOperatorsService operatorService;

	@Autowired
	IBusinessTypeService busService;

	@Autowired
	IUpShopProService productService;

	@Autowired
	IProvincialInformationService infoService;

	@Autowired
	IMatchingStrategyService iMatchingStrategyService;

	@Path("addUpProduct")
	@POST
	public String addUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole( request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleUp(user)){
			    			  //检查供货商下的产品编号是否唯一
			    			  UpShopProduct proOld = this.productService.findProductExits(json.getString("provinceuuid"),json.getString("operatoruid"),json.getString("busuuid"),
			    					  json.getString("useruuid"),json.getString("upfacevalue"),BigUtil.getBigDecimal(json.getString("price")),json.getString("productCode").trim());
			    			  if(proOld != null){
			    				  return ResultMessage.getFailt(ResultMessage.productCodeexistError);
			    			  }
			    			  UpShopProduct product = null;
			    			  product =  new UpShopProduct();
		    				  product.setBusinessType(busType);
			    			  product.setOperators(operator);
			    			  product.setProvincialInformation(pro);
			    			  product.setUser(user);
			    			  product.setProductCode(json.getString("productCode").trim());
			    			  product.setUpfacevalue(json.getString("upfacevalue"));
			    			  product.setPrice(BigUtil.getBigDecimal(json.getString("price").trim()));
			    			  product.setFastchargetype(json.getInt("fastchargetype"));
			    			  product.setUpfailnum(json.getInt("upfailnum"));
			    			  product.setUptimeinterva(json.getInt("uptimeinterva"));
			    			  product.setRemark(json.getString("remark"));
			    			  product.setDiscount(BigUtil.getBigDecimal(json.getString("discount").trim()));
			    			  product.setDiscountAmount(BigUtil.getBigDecimal(json.getString("discountAmount").trim()));
			    			  product.setModifytime(DateUtils.getNowDate());
			    			  product.setStatus(Config.publicStatus[1]+"");
			    			  product.setProductName(json.getString("productName"));
			    			  product.setValidity(json.getString("validity"));
							  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
//			    			  product.setDeduct(BigUtil.getBigDecimal(json.getString("deduct")));
//			    			  product.setDeductAmount(BigUtil.getBigDecimal(json.getString("deductAmount")));
			    			  String token = request.getHeader("token");
			    				if (token != null) {
			    					DecodedJWT jwt;
		    						jwt = JWT.decode(token);
		    						if (jwt != null) {
		    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
		    							if (json != null) {
		    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
		    								 if(productService.addUpshoppro(product,userAdmin)){
		    				    				  return ResultMessage.getSucceed(null);
		    				    			  }
		    				    			  return ResultMessage.getFailt("");
		    							}
		    						}
			    				}

			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}


	@Path("addBatchUpProduct")
	@POST
	public String addBatchUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype",
				"upfailnum","uptimeinterva","remark","products");
		logger.info(data);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleUp(user)){
			    			  JSONArray pros = json.getJSONArray("products");
			    			  boolean temp = false;
			    			  if(pros != null && !pros.isEmpty()){
			    				  String addProductResult = "";
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					  if(pros.getJSONObject(i).containsKey("productCode")){
			    						  UpShopProduct proOld = this.productService.findProductExits(json.getString("provinceuuid"),json.getString("operatoruid"),
				    							  json.getString("busuuid"),json.getString("useruuid"),pros.getJSONObject(i).getString("upfacevalue"),BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price")),pros.getJSONObject(i).getString("productCode").trim());
						    			  if(proOld != null){
				    						  temp = true;
				    						  addProductResult += "面值:"+pros.getJSONObject(i).getString("upfacevalue").concat(",原价:").concat(pros.getJSONObject(i).getString("price").concat("  "));
				    					  }
			    					  }else{
			    						  return ResultMessage.getFailt(ResultMessage.parameterError);
			    					  }
			    				  }
			    				  if(temp){
			    				  	  logger.info("失败相同面值:"+addProductResult);
			    					  return ResultMessage.getFailt(addProductResult.concat(Config.exist));
			    				  }
			    				  //
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					//检查供货商下的产品编号是否唯一
					    			  UpShopProduct product = null;
					    			  product =  new UpShopProduct();
				    				  product.setBusinessType(busType);
					    			  product.setOperators(operator);
					    			  product.setProvincialInformation(pro);
					    			  product.setUser(user);
					    			  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
					    			  product.setUpfacevalue(pros.getJSONObject(i).getString("upfacevalue"));
					    			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
					    			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
					    			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
					    			  product.setFastchargetype(json.getInt("fastchargetype"));
					    			  product.setUpfailnum(json.getInt("upfailnum"));
					    			  product.setUptimeinterva(json.getInt("uptimeinterva"));
					    			  product.setRemark(json.getString("remark"));
					    			  product.setModifytime(DateUtils.getNowDate());
									  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
									  product.setArtificial(json.getBoolean("artificial"));
									  product.setPressOrder(json.getBoolean("pressOrder"));
					    			  if(pros.getJSONObject(i).containsKey("productName")){
					    				  product.setProductName(pros.getJSONObject(i).getString("productName"));
					    			  }
					    			  product.setStatus(Config.publicStatus[1]+"");
					    			  product.setValidity(Config.validity[2]);
					    			  String token = request.getHeader("token");
					    				if (token != null) {
					    					DecodedJWT jwt;
				    						jwt = JWT.decode(token);
				    						if (jwt != null) {
				    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
				    							if (json != null) {
				    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
				    								 if(!productService.addUpshoppro(product,userAdmin)){
														 logger.info("保存失败:");
				    									 return ResultMessage.getFailt("");
				    				    			  }
				    							}
				    						}
					    				}
			    				  }
			    				  return ResultMessage.getSucceed(null);
			    			  }
			    			  return ResultMessage.getFailt(ResultMessage.parameterError);
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Path("findBatchUpProduct")
	@POST
	public String findBatchUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			return ResultMessage.getSucceed( JsonUtils.convertListToJson(this.productService.findBatchUpProduct(
					json.getString("provinceuuid"), json.getString("operatoruid"), json.getString("busuuid"),
					json.getString("useruuid"),json.getString("cityName")),
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","businessType","modifytime","operatoruid","provinceuuid","lastlogintime","password",
							"token","userstatus","usertype","useruuid","wechatid","provincialInformation","operators","user",""}));
		}
		return result;
	}


	@Path("editBatchUpProduct")
	@POST
	public String editBatchUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole( request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleUp(user)){
			    			  JSONArray pros = json.getJSONArray("products");
			    			  if(pros != null && !pros.isEmpty()){
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					  if(!pros.getJSONObject(i).containsKey("upprouuid")){
			    						  return addProduct(null, json, pros, i, pro, operator, user, busType, request);
			    					  }
			    					  UpShopProduct product = this.productService.findById(pros.getJSONObject(i).getString("upprouuid"));
					    			  if(product != null){
					    				  if(pros.getJSONObject(i).containsKey("productCode")){
					    					  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
					    				  }
						    			  product.setUpfacevalue(pros.getJSONObject(i).getString("upfacevalue"));
						    			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
						    			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
						    			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
						    			  product.setModifytime(DateUtils.getNowDate());
						    			  if(pros.getJSONObject(i).containsKey("productName")){
						    				  product.setProductName(pros.getJSONObject(i).getString("productName").trim());
						    			  }
						    			  product.setBusinessType(busType);
						    			  product.setOperators(operator);
						    			  product.setProvincialInformation(pro);
						    			  product.setUser(user);
										  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
										  product.setArtificial(json.getBoolean("artificial"));
										  product.setPressOrder(json.getBoolean("pressOrder"));
						    			  String token = request.getHeader("token");
						    				if (token != null) {
						    					DecodedJWT jwt;
					    						jwt = JWT.decode(token);
					    						if (jwt != null) {
					    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
					    							if (json != null) {
					    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
					    								 if(!productService.updateUpshoppro(product,userAdmin,false)){
					    									 return ResultMessage.getFailt("");
					    				    			  }
					    							}
					    						}
						    				}
					    			  }else{
					    				 return addProduct(product, json, pros, i, pro, operator, user, busType, request);
					    			  }
			    				  }
			    				  return ResultMessage.getSucceed(null);
			    			  }
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}
	private String addProduct(UpShopProduct product,JSONObject json,JSONArray pros,int i,ProvincialInformation pro,Operators operator,User user, BusinessType busType,HttpServletRequest request){
		 product = this.productService.findProductExits(json.getString("provinceuuid"),json.getString("operatoruid"),
				  json.getString("busuuid"),json.getString("useruuid"),pros.getJSONObject(i).getString("upfacevalue"),BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price")),pros.getJSONObject(i).getString("productCode").trim());
		  if(product == null){
			  product = new UpShopProduct();
			  product.setBusinessType(busType);
			  product.setOperators(operator);
			  product.setProvincialInformation(pro);
			  product.setUser(user);
			  if(pros.getJSONObject(i).containsKey("productCode")){
				  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
//				  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
			  }

			  product.setUpfacevalue(pros.getJSONObject(i).getString("upfacevalue"));
			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
			  product.setFastchargetype(json.getInt("fastchargetype"));
			  product.setUpfailnum(json.getInt("upfailnum"));
			  product.setUptimeinterva(json.getInt("uptimeinterva"));
//			  product.setRemark(json.getString("remark"));
			  product.setStatus(Config.publicStatus[1]+"");
			  product.setModifytime(DateUtils.getNowDate());
			  if(pros.getJSONObject(i).containsKey("productName")){
				  product.setProductName(pros.getJSONObject(i).getString("productName").trim());
			  }
			  String token = request.getHeader("token");
				if (token != null) {
					DecodedJWT jwt;
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
						if (json != null) {
							User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
							 if(!productService.updateUpshoppro(product,userAdmin,false)){
								 return ResultMessage.getFailt("");
			    			  }
						}
					}
				}
		  }else{
			  String addProductResult = "面值:"+pros.getJSONObject(i).getString("upfacevalue").concat(",原价:").concat(pros.getJSONObject(i).getString("price").concat("  "));
			  return ResultMessage.getFailt( addProductResult);
		  }
		  return ResultMessage.getFailt(ResultMessage.systemErrorParameter);
	  }


	@Path("updateUpProduct")
	@POST
	public String updateUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleUp(user)){
			    			  UpShopProduct product = this.productService.findById(json.getString("upprouuid"));
			    			  if(product != null){
			    				  product.setBusinessType(busType);
				    			  product.setOperators(operator);
				    			  product.setProvincialInformation(pro);
				    			  product.setUser(user);
				    			  product.setProductCode(json.getString("productCode").trim());
				    			  product.setUpfacevalue(json.getString("upfacevalue").trim());
				    			  product.setPrice(BigUtil.getBigDecimal(json.getString("price").trim()));
				    			  product.setFastchargetype(json.getInt("fastchargetype"));
//				    			  product.setUpfailnum(json.getInt("upfailnum"));
//				    			  product.setUptimeinterva(json.getInt("uptimeinterva"));
				    			  product.setRemark(json.getString("remark"));
				    			  product.setDiscount(BigUtil.getBigDecimal(json.getString("discount").trim()));
				    			  product.setDiscountAmount(BigUtil.getBigDecimal(json.getString("discountAmount").trim()));
				    			  product.setModifytime(DateUtils.getNowDate());
				    			  product.setProductName(json.getString("productName"));
				    			  product.setValidity(json.getString("validity"));
								  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
//				    			  if(json.containsKey("deduct") && !StringUtils.isBlank(json.getString("deduct"))){
//				    				  product.setDeduct(BigUtil.getBigDecimal(json.getString("deduct")));
//				    			  }
//				    			  if(json.containsKey("deductAmount") && !StringUtils.isBlank(json.getString("deductAmount"))){
//					    			  product.setDeductAmount(BigUtil.getBigDecimal(json.getString("deductAmount")));
//				    			  }

				    			  String token = request.getHeader("token");
				    				if (token != null) {
				    					DecodedJWT jwt;
			    						jwt = JWT.decode(token);
			    						if (jwt != null) {
			    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
			    							if (json != null) {
			    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
			    								 if(productService.updateUpshoppro(product,userAdmin,false)){
			    				    				  return ResultMessage.getSucceed(null);
			    				    			  }
			    				    			  return ResultMessage.getFailt("");
			    							}
			    						}
				    				}
			    			  }
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@POST
	@Path("findOneProduct")
	public String findOneProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "upprouuid");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return ResultMessage.getSucceed( JsonUtils.excludes(this.productService.findById(json.getString("upprouuid")),
					new String[]{"operatorsType","errorCodesForUseruuid","","status","modifytime","createtime","busCode","lastlogintime","password",
							"token","userstatus","usertype","","wechatid","code","provincecode","provincestatus","","","","","","","","","","",""}));
		}
		return result;
	}

	@Path("findPageProduct")
	@POST
	public String findPageProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();

			return ResultMessage.getSucceed( JsonUtils.excludes(this.productService.findPageUpshoppro(getPageMap(parameters, json), json.getInt("start"), json.getInt("pageSize")),
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","","modifytime","operatoruid","provinceuuid","lastlogintime","password",
							"token","userstatus","usertype","useruuid","wechatid"}));
		}
		return result;
	}

	private Map<String, Object> getPageMap(Map<String, Object> parameters,JSONObject json){
		if(!StringUtils.isBlank(json.getString("provinceuuid"))){
			parameters.put(":provinceuuid", json.getString("provinceuuid"));
		}
		if(!StringUtils.isBlank(json.getString("operatoruid"))){
			parameters.put(":operatoruid", json.getString("operatoruid"));
		}
		if(!StringUtils.isBlank(json.getString("busuuid"))){
			parameters.put(":busuuid", json.getString("busuuid"));
		}
		if(!StringUtils.isBlank(json.getString("useruuid"))){
			parameters.put(":useruuid", json.getString("useruuid"));
		}
		if(!StringUtils.isBlank(json.getString("productCode"))){
			parameters.put(":productCode", json.getString("productCode"));
		}
//		if(!StringUtils.isBlank(json.getString("upfacevalue"))){
//			parameters.put(":upfacevalue", BigUtil.getBigDecimal(json.getString("upfacevalue")));
//		}
		if(!StringUtils.isBlank(json.getString("fastchargetype"))){
			parameters.put(":fastchargetype", json.getInt("fastchargetype"));
		}
		if(json.containsKey("validity") && !StringUtils.isBlank(json.getString("validity"))){
			parameters.put(":validity", json.getString("validity"));
		}
		if(json.containsKey("cityName") && !StringUtils.isBlank(json.getString("cityName"))){
			parameters.put(":cityName", json.getString("cityName"));
		}
		if(json.containsKey("upfacevalue") && !StringUtils.isBlank(json.getString("upfacevalue"))){
			// json.getString("upfacevalue")
			parameters.put(":upfacevalue", json.getJSONArray("upfacevalue").join(","));
		}
		if(json.containsKey("status") && !StringUtils.isBlank(json.getString("status"))){
			parameters.put(":status", json.getString("status"));
		}

		return parameters;
	}

	@Path("exportUpProduct")
	@POST
	public String exportUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","productCode",
				"upfacevalue","fastchargetype");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();

			JSONObject obj = JsonUtils.getJSONOBJCT();
			String exportResult = ExportExcelUtil.exportUpProduct(this.productService.exportUpProduct(getPageMap(parameters, json)));
			if(exportResult != null){
				obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
				return ResultMessage.getSucceed(obj.toString());
			}else{
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	@Path("findOpeProBusShop")
	@POST
	public String findOpeProBusShop(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "");
		if(result == null){
			//运营商  省份 业务类型
			JSONObject json = JsonUtils.converToJson(data);
			json.put("operator", JsonUtils.jsonArrayToJson(operatorService.findAll(), new String[]{"createtime","status","remark","code","",""}));
			json.put("info", JsonUtils.jsonArrayToJson(infoService.findAllPro(), new String[]{"provincestatus","provincecode","createtime","remark","",""}));
			json.put("bus", JsonUtils.jsonArrayToJson(busService.findAllBus(), new String[]{"operatorsType","busCode","status","createtime","remark",""}));
			return ResultMessage.getSucceed( json.toString());
		}
		return result;
	}

	@Path("productEnable")
	@POST
	public String productEnable(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "upprouuid","status","useruuid");
		if(result == null){
			//运营商  省份 业务类型
			JSONObject json = JsonUtils.converToJson(data);
			UpShopProduct product = this.productService.findById(json.getString("upprouuid"));
			 User user = userService.findByUserid(json.getString("useruuid"));
			if(product != null && user != null && UserUtil.checkRole(user)){
				product.setStatus(json.getString("status"));
				this.productService.updateUpshoppro(product, user,true);
				return ResultMessage.getSucceed( json.toString());
			}
			return ResultMessage.getFailt( "没有对应的产品或者没有此权限");
		}
		return result;
	}


	/**
	 * 下游产品匹配查询
	 * @param data
	 * @param request
	 * @return
	 */
	@POST
	@Path("downProductMatchFind")
	public String downProductMatchFind(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "operatoruid","provinceuuid","busuuid","useruuids");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if(!StringUtils.isBlank(json.getString("operatoruid"))){
				parameters.put(":operatoruid", json.getString("operatoruid"));
			}
			if(!StringUtils.isBlank(json.getString("provinceuuid"))){
				parameters.put(":provinceuuid", json.getString("provinceuuid"));
			}
			if(!StringUtils.isBlank(json.getString("busuuid"))){
				parameters.put(":busuuid", json.getString("busuuid"));
			}
			if(!StringUtils.isBlank(json.getString("useruuids"))){
				parameters.put(":useruuids", json.getString("useruuids"));
			}
			if(json.containsKey("upfacevalue") && !StringUtils.isBlank(json.getString("upfacevalue"))){
				parameters.put(":upfacevalue", json.getString("upfacevalue"));
			}

			Page<UpShopProduct> productPage = this.productService.downProductMatchFind(parameters,json.getInt("start"),json.getInt("pageSize"));
			if(json.containsKey("downprouuid") && !StringUtils.isBlank(json.getString("downprouuid"))){
				for(int i = 0 ; i < productPage.getResult().size(); i++){
					UpShopProduct upShopProduct = productPage.getResult().get(i);
					//查询上游产品匹配的下游产品id
					MatchingStrategy matchingStrategy = iMatchingStrategyService.findByDownUuidUpFace(upShopProduct.getProvincialInformation().getProvinceuuid(),
							upShopProduct.getOperators().getOperatoruid(),
							upShopProduct.getBusinessType().getBusuuid(),upShopProduct.getUser().getUseruuid(),
							upShopProduct.getUpfacevalue(),json.getString("downprouuid"));
					if(matchingStrategy != null){
						upShopProduct.setRemark(matchingStrategy.getDownprouuid());
					}
				};
			}else if(json.containsKey("downprouuids") && json.getJSONArray("downprouuids").size() > 0){
				for(int j = 0 ; j < json.getJSONArray("downprouuids").size(); j++){
					for(int i = 0 ; i < productPage.getResult().size(); i++){
						UpShopProduct upShopProduct = productPage.getResult().get(i);
						//查询上游产品匹配的下游产品id
						MatchingStrategy matchingStrategy = iMatchingStrategyService.findByDownUuidUpFace(upShopProduct.getProvincialInformation().getProvinceuuid(),
								upShopProduct.getOperators().getOperatoruid(),
								upShopProduct.getBusinessType().getBusuuid(),upShopProduct.getUser().getUseruuid(),
								upShopProduct.getUpfacevalue(),json.getJSONArray("downprouuids").getJSONObject(j).getString("downprouuid"));
						if(matchingStrategy != null){
							upShopProduct.setRemark(matchingStrategy.getDownprouuid());
						}
					};
				}
			}

			return ResultMessage.getSucceed( JsonUtils.excludes(productPage,
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","","modifytime","operatoruid","provinceuuid","lastlogintime","password",
							"token","userstatus","usertype","useruuid","wechatid"}));
		}
		return result;
	}


	@Path("editBatchPhoneUpProduct")
	@POST
	public String editBatchPhoneUpProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype",
				"upfailnum","uptimeinterva","remark","products");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleUp(user)){
			    			  JSONArray pros = json.getJSONArray("products");
			    			  if(pros != null && !pros.isEmpty()){
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					  if(!pros.getJSONObject(i).containsKey("upprouuid")){
			    						  return addProduct(null, json, pros, i, pro, operator, user, busType, request);
			    					  }
			    					  UpShopProduct product = this.productService.findById(pros.getJSONObject(i).getString("upprouuid"));
					    			  if(product != null){
					    				  if(pros.getJSONObject(i).containsKey("productCode")){
					    					  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
					    				  }
						    			  product.setUpfacevalue(pros.getJSONObject(i).getString("upfacevalue"));
						    			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
						    			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
						    			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
//						    			  product.setDeduct(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("deduct").trim()));
//						    			  product.setDeductAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("deductAmount").trim()));
						    			  product.setModifytime(DateUtils.getNowDate());
						    			  if(pros.getJSONObject(i).containsKey("productName")){
						    				  product.setProductName(pros.getJSONObject(i).getString("productName").trim());
						    			  }
						    			  product.setBusinessType(busType);
						    			  product.setOperators(operator);
						    			  product.setProvincialInformation(pro);
						    			  product.setUser(user);
						    			  String token = request.getHeader("token");
						    				if (token != null) {
						    					DecodedJWT jwt;
					    						jwt = JWT.decode(token);
					    						if (jwt != null) {
					    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
					    							if (json != null) {
					    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
					    								 if(!productService.updateUpshoppro(product,userAdmin,true)){
					    									 return ResultMessage.getFailt("");
					    				    			  }
					    							}
					    						}
						    				}
					    			  }else{
					    				 return addProduct(product, json, pros, i, pro, operator, user, busType, request);
					    			  }
			    				  }
			    				  return ResultMessage.getSucceed(null);
			    			  }
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Path("findByUuidProduct")
	@POST
	public String findByUuidProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "useruuid");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			return ResultMessage.getSucceed( JsonUtils.convertListToJson(productService.getProductList(json.getString("useruuid")),
					new String[]{"provincialInformation","operators","businessType","user","upfacevalue","validity","upfacevalue","discount",
							"status","createtime","modifytime","fastchargetype","upfailnum","uptimeinterva","remark","productCode","price",
							"discountAmount","deduct","deductAmount"}));
		}
		return result;
	}

	/**
	 * 更新是否转人工状态
	 * @param data
	 * @param request
	 * @return
	 */
	@POST
	@Path("updateProductArtificial")
	public  String updateArtificial(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService, "upprouuid","artificial");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return productService.updateArtificial(json);
		}
		return result;
	}

	/**
	 * 是否压单 1 转压单 0 不压单
	 * @param data
	 * @param request
	 * @return
	 */
	@POST
	@Path("updateProductPressOrder")
	public  String updatePressOrder(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService, "upprouuid","pressOrder");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return this.productService.updatePressOrder(json);
		}
		return result;
	}


	/**
	 * 匹配产品查询
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("findPageProductDown")
	@POST
	public String findPageProductDown(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return ResultMessage.getSucceed(
					this.productService.findPageProductDown(json, json.getInt("start"), json.getInt("pageSize")));
		}
		return result;
	}



	@Path("deleteUpProduct")
	@POST
	public String deleteDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			return productService.deleteDownProduct(data);
		}
		return result;
	}

}
